<template>
    <eui-page-frame topHeight="710">
        <template #top>
            <view class="content-img">
                <eui-nav-bar ref="BcmNavBar" title="拣货" :storeName="sUserStoreName" :storeId="sUserStore"
                    @onClickStore="clickStore" color="#333"
                    backgroundColor="white" @onClickRefresh="onClickRefresh"/>
                <view class="container">
                    <scroll-view class="scroll-view" scroll-x scroll-with-animation scroll-animation-duration="230">
                        <view :class="activeKey == item.value ? 'item on' : 'item'" v-for="(item, index) in statusList"
                            :key="index" @click="changeTab(item.value)">
                            <view class="name" style="font-size: 32rpx;">{{ item.text }}</view>
                            <view class="border"
                                :style="{ 'background': activeKey == item.value ? 'linear-gradient(159deg, #4FE0EA 0%, #85B6FD 100%)' : '#fff' }">
                            </view>
                            <view class="number" v-if="item.number > 0 && item.number < 100">{{ item.number }}</view>
                            <view class="number" v-if="item.number >= 100">99+</view>
                        </view>
                    </scroll-view>
                </view>
                <view style="padding: 12rpx 0 12rpx 16rpx;" class="bg-white">
                    <scroll-view scroll-x scroll-with-animation scroll-animation-duration="240" class="orderno-scroll-view" style="font-size: 24rpx;"  @scrolltolower="orderNoListPullUp">
                        <view :class="orderNo == ''?'text-center orderno co-white active':'text-center orderno'" @click="changeOrdreNoTab('')" v-if="orderNoList.length" style="padding: 28rpx 0;">
                            <view class="bold">全部订单</view>
                            <view>{{ OrderListRowsCount }}件</view>
                        </view>
                        <view v-for="(item, index) in orderNoList" 
                        :key="index" @click="changeOrdreNoTab(item.orderNo)" :class="orderNo == item.orderNo?'text-center orderno co-white active':'text-center orderno'">
                            <OrdreCount :currentTime="currentTime" :expectPickupTime="item.expectPickupTime" />
                            <view class="bold">
                                <text v-if="getBcmDictName('chnlType', item.chnlType)" style="line-height: 32rpx;">{{ getBcmDictName('chnlType', item.chnlType)?.substring(0,1) }}</text>
                                <text v-if="item.thirdOrderIndex"  style="line-height: 32rpx;margin-left: 4rpx">#{{ item.thirdOrderIndex }}</text>
                            </view>
                            <view style="margin-bottom: 20rpx;">
                                <text style="display: inline-block;background-color: #FFC00B;padding: 0 3rpx;border-radius: 6rpx;margin-right: 4rpx;" class="co-white text-center">注</text>
                                <text>{{ item.orderGoodsNum }}件</text>
                            </view>
                        </view>
                    </scroll-view>
                </view>
                <view style="padding: 0 25rpx;max-height: 400rpx;overflow-y: auto;" class="bg-white">
                    <scroll-view scroll-y scroll-with-animation scroll-animation-duration="240" style="font-size: 24rpx;" class="remarkBox" @scrolltolower="orderNoListPullUp">
                        <view v-for="(item, index) in orderNoList.filter(v=> (!!orderNo && (v.buyerRemark && v.orderNo == orderNo)) || (!orderNo && v.buyerRemark))" 
                        :key="index" class="flex align-center remarkitem">
                            <view class="text-center bg-white" style="border: 1rpx solid #979797;width: 118rpx;padding: 4rpx 0;">
                                <view>
                                    <text v-if="getBcmDictName('chnlType', item.chnlType)" style="line-height: 32rpx;">{{ getBcmDictName('chnlType', item.chnlType)?.substring(0,1) }}</text>
                                    <text v-if="item.thirdOrderIndex"  style="line-height: 32rpx;">#{{ item.thirdOrderIndex }}</text>
                                </view>
                                <view>备注</view>
                            </view>
                            <view style="color: #FF0000;margin-left: 9rpx;">{{ item.buyerRemark }}</view>
                        </view>
                    </scroll-view>
                </view>
            </view>
        </template>
        <view class="footer-view">
            <scroll-view style="width: 140rpx;background-color: #F2F2F2;font-size: 24rpx;">
                <view v-for="(item, index) in areaList" :key="index" @click="changeAreaTab(item?.areaCode)"
                    :class="areaCode == item?.areaCode ? 'bg-white text-center' : 'text-center'"
                    style="width: 100%;padding: 13rpx 0;">
                    <view :class="areaCode == item?.areaCode ? 'bold' : ''" style="font-size: 24rpx;">{{ item?.areaName
                        }}
                    </view>
                    <view style="color: #5E5E5E;">{{ item?.goodsNum }}件</view>
                </view>
            </scroll-view>
            <eui-virtual-list @onRefresh="listPullDown" @lower="listPullUp" refresher="true" isBottom="true"
                :origList="orderList" type="list" :showHeard="false" style="flex: 1;">
                <template v-slot:list="scope">
                    <view class="flex just-between">
                        <view>
                            <image class="goods-image" :src="scope.goodsPicUrl" v-if="!!scope.goodsPicUrl"
                            @tap="previewImage" lazy-load mode="scaleToFill"></image>
                            <image v-else class="goods-image" src="../../../static/img/110.png"></image>
                            <view style="font-size: 28rpx;color: #8e8e8e;padding-left: 20rpx;margin-bottom: 10rpx;" v-if="scope.spec">规格: <text style="color: red">{{ scope.spec }}</text></view>
                            <view style="height: 32rpx;line-height: 32rpx;color: #767676; font-size: 24rpx;border: 1px solid #979797;border-radius: 4rpx;margin: 0 27rpx;" class="text-center"  >
                                <text v-if="getBcmDictName('chnlType', scope.chnlType)" style="line-height: 32rpx;">{{ getBcmDictName('chnlType', scope.chnlType)?.substring(0,1) }}</text>
                                <text v-if="scope.thirdOrderIndex"  style="line-height: 32rpx;">#{{ scope.thirdOrderIndex }}</text>
                            </view>
                        </view>
                        <view style="margin-left: 11rpx;font-size: 28rpx;line-height: 40rpx;">
                            <view class="co-00 bold text-elips" style="font-size:32rpx;line-height: 45rpx;" >{{ scope.goodsName }}
                            </view>
                            <view class="flex">
                                <view><text style="color: #8e8e8e;">数量: </text><text class="bold">{{ scope.goodsNum
                                        }}</text></view>
                                <view style="margin-left: 100rpx;"><text style="color: #8e8e8e;">价格: </text><text class="bold">{{
                    formatPrice(scope.actualPrice * scope.goodsNum) }}</text></view>
                            </view>
                            <view><text style="color: #8e8e8e;">商品编码: </text><text class="bold">{{ scope.goodsCode
                                    }}</text></view>
                            <view><text style="color: #8e8e8e;">商品条码: </text><text class="bold">{{ scope.goodsBarcode
                                    }}</text></view>
                        </view>
                    </view>
                </template>
                <template v-slot:bottom="scope">
                    <view>
                        <eui-button :modelValue="scope" title="接单" type="max" v-if="activeKey == '0'"
                            @buttonClick="buttonClick" single-tag="confrim"></eui-button>
                        <eui-button :modelValue="scope" title="缺货" :type="'max2'" single-tag="submit"
                            v-if="activeKey == '1'" @buttonClick="buttonClick"></eui-button>
                        <eui-button :modelValue="scope" title="拣货完成" type="max" single-tag="picking"
                            v-if="activeKey == '1'" @buttonClick="buttonClick" style="margin-left: 20rpx;"></eui-button>
                    </view>
                </template>
            </eui-virtual-list>
            <eui-popup ref="pickOrdreGdsPopup" background-color="#fff" type="bottom" :mask-click="false">
                <view class="popup-content">
                    <view class="popup-title flex just-between">
                        <view style="font-weight: bold;">
                            缺货拣货
                        </view>
                        <bcm-close-btn @click="closePickOrderGdsPopup" />
                    </view>
                    <view
                        style="padding-left: 30rpx;color: #000;background-color:#fff;box-sizing: border-box;padding-top:24rpx;font-size: 32rpx; line-height: 32rpx;height: 30vh;">
                        <eui-card-input  type="text"  v-model="currentItem.goodsNum" title="应拣数量" showBottomLine="false" alignType="left" :showBottomLine="false" disabled/>
                        <eui-card-input  type="number" required  v-model="currentItem.pickNum" title="实拣数量" showBottomLine="false" alignType="left" :showBottomLine="false" />
                    </view>
                    <view class="bottom-1">
                        <eui-button type="max2" @buttonClick="closePickOrderGdsPopup" title="关闭" style="width: 40%;" />
                        <eui-button @buttonClick="stockBtnClick" title="拣货完成" style="width: 40%;" type="max" />
                    </view>
                </view>
            </eui-popup>
        </view>
    </eui-page-frame>
</template>
<script setup type="ts">
import { ref, reactive, onMounted, onUnmounted } from 'vue';
import service from '@/common/service';
import { getBcmUrl, bcmRequest } from '../../../hooks/bcmServices';
import { getBcmDictList, getBcmDictName, getBcmDictItem, formatPrice } from '../../../hooks/bcmUseUntils';
import { onLoad, onShow } from "@dcloudio/uni-app";
import { useMainStore } from "@/store/modules/store";
import BcmCloseBtn from '../components/BcmCloseBtn';
import OrdreCount from './components/OrderCount'
import { init, onClickRefresh} from '../../../hooks/bcmInit';
import Enjoy from "../../../common/enjoy"
import BcmEventType from "@/pages/BcmViews/common/BcmEventType";

const mainStore = useMainStore();
const { loginInfo } = mainStore;
const bcmUrl = getBcmUrl();

const BcmNavBar = ref(null);
const sUserStore = ref('');
const sUserStoreName = ref('');
const sUser = ref('');

const CurrentPage = ref(1); //第几页
const PageSize = ref(10); //每页10条
const RowsCount = ref(0); //总条数
const PageCount = ref(1); //总页数

const AreaCurrentPage = ref(1); //第几页
const AreaRowsCount = ref(0); //总条数
const AreaPageSize = ref(10); //每页10条
const AreaPageCount = ref(1); //总页数

const OrderListCurrentPage = ref(1); //第几页
const OrderListRowsCount = ref(0); //总条数
const OrderListPageSize = ref(10); //每页10条
const OrderListPageCount = ref(1); //总页数
const orderNoList = ref([]);

const orderList = ref([]);
const orderNo = ref('');
const areaList = ref([]);
const areaCode = ref('');
const pickOrdreGdsPopup = ref(false)
const currentItem = ref({
    goodsNum: 0,
    pickNum: 0
})

const statusList = ref([{
    text: '待接单',
    value: '0',
    number: 0
}, {
    text: '待拣货',
    value: '1',
    number: 0
}, {
    text: '已完成',
    value: '2',
    number: 0
}])

const activeKey = ref('0')

const timer = ref(null)
const chnlTypeList = ref([])
const currentTime = ref(null)

const startTimer = () => {
    stopTimer();
    timer.value = setInterval(() => {
        currentTime.value = new Date().getTime();
    }, 1000);
}

const stopTimer = () => {
    // 停止定时器
    clearInterval(timer.value);
    timer.value = null;
}

const changeTab = (value) => {
    activeKey.value = value;
    areaCode.value = '';
    orderNo.value = '';
    orderList.value = [];
    fetchOrderData();
    fetchAreaData();
    fetchOrderListData()
}

const changeOrdreNoTab = (value) => {
    orderNo.value = value;
    areaCode.value = '';
    orderList.value = [];
    fetchOrderData();
    fetchAreaData()
}

const changeAreaTab = (value) => {
    areaCode.value = value;
    fetchOrderData();
}

const setDefault = () => {
    sUserStore.value = loginInfo?.sDefaultStore ? loginInfo.sDefaultStore : loginInfo.sUserStore;
    sUserStoreName.value = loginInfo?.sDefaultStoreName ? loginInfo.sDefaultStoreName :loginInfo.sUserStoreName;
    sUser.value = loginInfo.sUser;
}

// 选择框点击事件
const clickStore = () => {
    let parms = Enjoy.GetDialogParms();
    parms.CallBack = SelectionChanged;
    parms.SelectionType = "机构选择";
    parms.SelectedItems = sUserStore.value;
    Enjoy.OpenDialog(parms)
}

const SelectionChanged = (event) => {
    if (event.SelectionType == '机构选择') {
        // 更新机构信息
        sUserStoreName.value = event.BackParms.Value;
        sUserStore.value = event.BackParms.Key;
        mainStore.switchStore(event.BackParms.Type, sUserStore.value, sUserStoreName.value);
        uni.$emit(BcmEventType.SWITCH_STORE,{msg:'切换门店'})
        // 按新条件获取数据
        fetchOrderData();
        fetchAreaData()
        staOrderStatus();
    }
}
// 列表下拉刷新
const listPullDown = (e) => {
    fetchOrderData();
    staOrderStatus();
}
// 列表上拉加载
const listPullUp = (e) => {
    if (CurrentPage.value < PageCount.value) {
        CurrentPage.value = CurrentPage.value + 1;
        fetchOrderData(true);
    }
}

const orderNoListPullUp = (e) => {
    if (OrderListCurrentPage.value < OrderListPageCount.value) {
        OrderListCurrentPage.value = OrderListCurrentPage.value + 1;
        fetchOrderListData(true);
    }
}

const previewImage = () => {

}


const closePickOrderGdsPopup = () => {
    pickOrdreGdsPopup.value.close()
}

const buttonClick = (e) => {
    let { singleTag, modelValue } = e;
    switch (singleTag) {
        case 'confrim':
            orderAction({
                uniqueKey: '订单商品表',
                methodName: 'AreaPickGoodsReceive'
            }, modelValue, undefined, '接单成功！')
            break;
        case 'picking':
            orderAction({
                uniqueKey: '订单商品表',
                methodName: 'AreaPickGoodsPickingComplete'
            }, modelValue, { pickNum: modelValue.goodsNum }, '拣货完成')
            break;
        case 'submit':
            currentItem.value = modelValue;
            currentItem.value.pickNum = modelValue.goodsNum;
            pickOrdreGdsPopup.value.open('bottom')
            break;
    }
}

const stockBtnClick = () => {
    if(!currentItem.value.pickNum && currentItem.value.pickNum!=0 || currentItem.value.pickNum == ''){
        uni.showToast({
            title: '请输入实拣数量！',
            icon: 'none'
        })
        return 
    }
    if(currentItem.value.pickNum - currentItem.value.goodsNum>0){
        uni.showToast({
            title: '实拣数量不可大于应拣数量！',
            icon: 'none'
        })
        return 
    }
    orderAction({
        uniqueKey: '订单商品表',
        methodName: 'AreaPickGoodsPickingComplete'
    }, currentItem.value, { pickNum: currentItem.value.pickNum }, '缺货拣货完成', true)
}

const orderAction = async ({
    uniqueKey,
    methodName
}, v, params = undefined, text = '', popup = false) => {
    service.enjoyShowLoading('正在加载...');
    const { goodsBarcode, goodsCode, orderGoodsId, orderNo } = v;
    let param;
    if (methodName == 'AreaPickGoodsReceive') {
        param = [{
            BillId: v.orderGoodsId
        }]
    } else {
        param = {
            goodsBarcode,
            goodsCode,
            orderGoodsId,
            orderNo,
            pickNum: params.pickNum,
            stockoutNum: v.goodsNum - params.pickNum
        }
    }

    const response = await bcmRequest(bcmUrl.orderApi, uniqueKey, methodName, param);
    service.enjoyHideLoading();
    if (text) {
        uni.showToast({
            title: text,
            icon: 'none',
            duration: 2000
        });
    }
    await fetchOrderData();
    await staOrderStatus();
    await fetchAreaData();
    await fetchOrderListData();
    if (popup) {
        closePickOrderGdsPopup()
    }
    if (params) {
        return response
    }
}

const fetchAreaData = async (e = undefined) => {
    service.enjoyShowLoading('正在加载...');
    if (!e) {
        AreaCurrentPage.value = 1;
    }
    const param = {
        IsNotPage: false,
        CurrentPage: AreaCurrentPage.value,
        PageSize: AreaPageSize.value,
        WhereList: [
            { c_col: "storeCode", c_oper: "等于", c_value: sUserStore.value, c_logic: "而且" },
            { c_col: "status", c_oper: "等于", c_value: activeKey.value },
            { c_col: "orderNo", c_oper: "等于", c_value: orderNo.value }
        ]
    }
    const response = await bcmRequest(bcmUrl.orderApi, '订单商品表', 'QueryAreaPickGoodsAreaStatistics', param);
    service.enjoyHideLoading();
    // AreaCurrentPage.value = response.CurrentPage; //第几页
    // AreaPageSize.value = response.PageSize; //每页10条
    // AreaRowsCount.value = response.RowsCount; //总条数
    // AreaPageCount.value = response.PageCount; //总页数
    areaList.value = response;
    // if (response.CurrentPage == 1) {
    //     areaList.value = response;
    // } else {
    //     areaList.value = areaList.value.concat(response);
    // }
}

const fetchOrderListData = async (e = undefined) => {
    if (!e) {
        OrderListCurrentPage.value = 1;
    }
    const param = {
        IsNotPage: false,
        CurrentPage: OrderListCurrentPage.value,
        PageSize: OrderListPageSize.value,
        WhereList: [
            { c_col: "storeCode", c_oper: "等于", c_value: sUserStore.value, c_logic: "而且" },
            { c_col: "status", c_oper: "等于", c_value: activeKey.value }
        ]
    }
    const response = await bcmRequest(bcmUrl.orderApi, '订单表', 'QueryAreaPickOrderList', param);
    OrderListCurrentPage.value = response.CurrentPage; //第几页
    OrderListPageSize.value = response.PageSize; //每页10条
    OrderListRowsCount.value = response.RowsCount; //总条数
    OrderListPageCount.value = response.PageCount; //总页数
    if (response.CurrentPage == 1) {
        orderNoList.value = response.ReturnObject;
    } else {
        orderNoList.value = orderNoList.value.concat(response.ReturnObject);
    }
}


const fetchOrderData = async (e = undefined) => {
    service.enjoyShowLoading('正在加载...');
    if (!e) {
        CurrentPage.value = 1;
    }
    const param = {
        IsNotPage: false,
        CurrentPage: CurrentPage.value,
        PageSize: PageSize.value,
        WhereList: [
            { c_col: "storeCode", c_oper: "等于", c_value: sUserStore.value, c_logic: "而且" },
            { c_col: "status", c_oper: "等于", c_value: activeKey.value },
            { c_col: "orderNo", c_oper: "等于", c_value: orderNo.value },
            { c_col: "areaCode", c_oper: "等于", c_value: areaCode.value }
        ]
    }
    const response = await bcmRequest(bcmUrl.orderApi, '订单商品表', 'QueryAreaPickGoodsAreaList', param);
    service.enjoyHideLoading();
    CurrentPage.value = response.CurrentPage; //第几页
    PageSize.value = response.PageSize; //每页10条
    RowsCount.value = response.RowsCount; //总条数
    PageCount.value = response.PageCount; //总页数
    if (response.CurrentPage == 1) {
        orderList.value = response.ReturnObject;
    } else {
        orderList.value = orderList.value.concat(response.ReturnObject);
    }
}

const staOrderStatus = async () => {
    const response = await bcmRequest(bcmUrl.orderApi, '订单商品表', 'QueryAreaPickOrderGoodsStatistics', {
        storeCode: sUserStore.value
    });

    statusList.value.forEach(a => {
        let item = response.find(v => v.status == a.value)
        a.number = item?.goodsRowNum || 0
    })
}

onMounted(() => {
    chnlTypeList.value = getBcmDictList('chnlType')
})

onShow(async () => {
    if(sUserStore.value){
        await staOrderStatus();
        await fetchOrderData();
    }
})

onLoad(async () => {
    await init();
    setDefault();
    if (!loginInfo.sUserStore) {
        BcmNavBar.value.onClickStore();
        return;
    }
    startTimer()
    await staOrderStatus();
    await fetchOrderData();
    await fetchAreaData()
    await fetchOrderListData()
})

onUnmounted(() => {
    stopTimer()
})

defineExpose({
    SelectionChanged
})
</script>
<style lang="scss" scoped>
@import "../../../main.scss";
@import "../common/common.css";

.content {
  display: flex;
  box-sizing: border-box;
  overflow-x: hidden;
  width: 100%;
  height: 100%;

//background-color: $uni-background;
  padding: 0;
}

.footer-view {
  display: flex;
  overflow-y: auto;
  width: 100%;
  height: 100%;
  background: $uni-bg-color;
}

::v-deep .white-main {
  right: 0;
  left: 0;
}

.on {
  color: rgba(2, 183, 230, 1);
  font-weight: bold;
}

.border {
  position: absolute;
  bottom: 0;
  left: 105rpx;
  width: 36rpx;
  height: 14rpx;
  border-bottom: none;
}

.content-img {
  position: relative;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  align-items: stretch;
  flex: 1;
  box-sizing: border-box;
  background-repeat: no-repeat;

//background: $uni-background-img;
  background-size: 100% 150px;
}

.navigation {
  flex: 0 0 auto;
}

.footer {
  flex: 1;
  box-sizing: border-box;
  padding: 0;
  margin: 0;
}

.bottom-1 {
  display: flex;
  justify-content: center;
  flex: 0 0 auto;
  height: 70rpx;
  padding: $uni-spacing-col-sm * 2 $uni-spacing-row-sm;
}

.goods-image {
  width: 140rpx;
  height: 140rpx;
  border-radius: 4rpx;
}

.popup-content {
  display: flex;
  flex-direction: column;
  width: 100%;
  padding: 0;
  background-color: #fff;

  .popup-title {
    display: flex;
    align-items: center;
    box-sizing: border-box;
    width: 100%;
    height: 100rpx;
    padding-right: 36rpx;
    padding-left: 30rpx;
    font-size: 33rpx;
    line-height: 100rpx;
    border-bottom: 1px solid #f1f1f1;
  }

  textarea {
    box-sizing: border-box;
    width: 100%;
    height: 80px;
    padding: 5px;
    margin: 5px 0;
    border: 1px solid #ccc;
    border-radius: 5px;
  }
}

.container {
  box-sizing: border-box;
  width: 100%;
  height: 80rpx;
  color: #000;

// padding: 0 20rpx 0 0;
  font-size: 14px;
  background-color: #fff;
  border-bottom: 2rpx solid #fff;
}

.scroll-view {
  display: flex;
  justify-content: space-around;
  align-items: center;
  box-sizing: border-box;
  overflow-x: auto;
  width: 100%;
  height: 100%;
  white-space: nowrap;
}

.orderno-scroll-view {
  display: flex;
  align-items: center;
  box-sizing: border-box;
  overflow-x: auto;
  width: 100%;
  height: 100%;
  white-space: nowrap;
}

.item {
  position: relative;
  display: inline-block;
  box-sizing: border-box;
  width: 250rpx;
  height: 80rpx;
  line-height: 80rpx;
  text-align: center;
  text-align: center;
}

.number {
  position: absolute;
  top: 0;
  right: 10rpx;
  height: 30rpx;
  padding: 2px 6px;
  color: #fff;
  font-size: 12px;
  line-height: 30rpx;
  background-color: #f00;
  border-radius: 10px;
}

.orderno {
  display: inline-block;
  box-sizing: border-box;
  width: 129rpx;
  height: 110rpx;
  margin-right: 24rpx;
  background: #eee;
  border-radius: 8rpx;
}

.active {
  background: linear-gradient( 200deg, #59e3ea 0%, #197cd8 100%, #e4d48d 100%);
}

.remarkitem {
  box-sizing: border-box;
  width: 100%rpx;
  height: 110rpx;
  padding: 17rpx 0;
  border-bottom: 1rpx solid #979797;
}

.over {
  width: 114rpx;
  height: 30rpx;
  margin-left: 15rpx;
  line-height: 30rpx;
  border-radius: 0rpx 6rpx 0rpx 6rpx;
}

.remarkBox .remarkitem:nth-last-child(1) {
  border: none;
}

.text-elips {
  display: -webkit-box;
  overflow: hidden;
  text-overflow: ellipsis;

  -webkit-box-orient: vertical;
  -webkit-line-clamp: 2;
}

::v-deep .list_scroll .list_cell {
  box-sizing: border-box;
  padding: 15rpx 14rpx 14rpx 0rpx;
  margin: 0;
  border-bottom: 1rpx solid #979797;
  border-radius: 0;
}

::v-deep .list_scroll .list_cell .item_view {
  box-sizing: border-box;
  padding: 0 10rpx;
}

::v-deep .list_scroll .list_cell:nth-last-child(1) {
  border: none;
}
</style>
